#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Retcode Analysis Report Generator
Generates detailed HTML format test reports
"""

import json
import os
from datetime import datetime
import argparse

def generate_html_report(json_file, output_file=None):
    """Generate HTML format retcode analysis report"""
    
    # Read JSON data
    try:
        with open(json_file, 'r', encoding='utf-8') as f:
            data = json.load(f)
    except FileNotFoundError:
        print(f"Error: File not found {json_file}")
        return
    except json.JSONDecodeError:
        print(f"Error: {json_file} is not a valid JSON file")
        return
    
    # Generate output filename
    if output_file is None:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        output_file = f"retcode_report_{timestamp}.html"
    
    # Prepare data
    start_time = datetime.fromtimestamp(data['start_time'])
    export_time = datetime.fromtimestamp(data['export_time'])
    duration = export_time - start_time
    
    retcode_stats = data['retcode_stats']
    total_requests = data['total_requests']
    success_rate = data['success_rate']
    error_rate = data['error_rate']
    
    # Generate HTML content
    html_content = f"""
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Locust Load Test - Retcode Analysis Report</title>
    <style>
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }}
        .container {{
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #2c3e50;
            text-align: center;
            margin-bottom: 30px;
            border-bottom: 3px solid #3498db;
            padding-bottom: 10px;
        }}
        h2 {{
            color: #34495e;
            margin-top: 30px;
            margin-bottom: 15px;
        }}
        .summary {{
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }}
        .summary-card {{
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            text-align: center;
        }}
        .summary-card.success {{
            background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
        }}
        .summary-card.error {{
            background: linear-gradient(135deg, #f44336 0%, #da190b 100%);
        }}
        .summary-card h3 {{
            margin: 0 0 10px 0;
            font-size: 1.2em;
        }}
        .summary-card .value {{
            font-size: 2em;
            font-weight: bold;
        }}
        table {{
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }}
        th, td {{
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }}
        th {{
            background-color: #3498db;
            color: white;
        }}
        tr:hover {{
            background-color: #f5f5f5;
        }}
        .success-row {{
            background-color: #d4edda;
        }}
        .error-row {{
            background-color: #f8d7da;
        }}
        .info {{
            background-color: #e7f3ff;
            border: 1px solid #b3d9ff;
            border-radius: 5px;
            padding: 15px;
            margin: 20px 0;
        }}
        .chart-container {{
            margin: 20px 0;
            text-align: center;
        }}
    </style>
</head>
<body>
    <div class="container">
        <h1>🚀 Locust Load Test - Retcode Analysis Report</h1>
        
        <div class="info">
            <strong>📊 Test Information</strong><br>
            Test Start Time: {start_time.strftime('%Y-%m-%d %H:%M:%S')}<br>
            Report Generation Time: {export_time.strftime('%Y-%m-%d %H:%M:%S')}<br>
            Test Duration: {duration}<br>
        </div>
        
        <h2>📈 Overall Statistics</h2>
        <div class="summary">
            <div class="summary-card">
                <h3>Total Requests</h3>
                <div class="value">{total_requests:,}</div>
            </div>
            <div class="summary-card success">
                <h3>Success Rate</h3>
                <div class="value">{success_rate:.2f}%</div>
            </div>
            <div class="summary-card error">
                <h3>Error Rate</h3>
                <div class="value">{error_rate:.2f}%</div>
            </div>
        </div>
        
        <h2>📋 Retcode Detailed Distribution</h2>
        <table>
            <thead>
                <tr>
                    <th>Retcode</th>
                    <th>Status</th>
                    <th>Request Count</th>
                    <th>Percentage</th>
                    <th>Description</th>
                </tr>
            </thead>
            <tbody>
"""
    
    # Generate retcode table rows
    sorted_retcodes = sorted(retcode_stats.items(), key=lambda x: x[1], reverse=True)
    
    retcode_descriptions = {
        0: "Request successful",
        1: "General business error",
        2: "Parameter error",
        3: "Permission error",
        4: "Resource not found",
        5: "Server internal error",
        'http_error': "HTTP request failed",
        'json_parse_error': "JSON parsing failed"
    }
    
    for retcode, count in sorted_retcodes:
        percentage = (count / total_requests) * 100 if total_requests > 0 else 0
        
        if retcode == 0:
            row_class = "success-row"
            status = "✅ Success"
        elif retcode in ['http_error', 'json_parse_error']:
            row_class = "error-row"
            status = "❌ System Error"
        else:
            row_class = "error-row"
            status = "❌ Business Error"
        
        description = retcode_descriptions.get(retcode, "Unknown error type")
        
        html_content += f"""
                <tr class="{row_class}">
                    <td><strong>{retcode}</strong></td>
                    <td>{status}</td>
                    <td>{count:,}</td>
                    <td>{percentage:.2f}%</td>
                    <td>{description}</td>
                </tr>
"""
    
    # Complete HTML
    html_content += """
            </tbody>
        </table>
        
        <h2>💡 Analysis Suggestions</h2>
        <div class="info">
"""
    
    # Generate analysis suggestions
    if success_rate >= 95:
        html_content += "<strong>✅ System Performance Excellent</strong><br>Success rate above 95%, system running stable."
    elif success_rate >= 90:
        html_content += "<strong>⚠️ System Performance Good</strong><br>Success rate between 90-95%, recommend investigating error causes."
    elif success_rate >= 80:
        html_content += "<strong>⚠️ System Performance Average</strong><br>Success rate between 80-90%, system performance optimization needed."
    else:
        html_content += "<strong>❌ System Performance Poor</strong><br>Success rate below 80%, urgent system issues need to be addressed."
    
    # Error analysis
    error_retcodes = [k for k, v in retcode_stats.items() if k != 0 and v > 0]
    if error_retcodes:
        html_content += "<br><br><strong>Main Error Types:</strong><br>"
        for retcode in error_retcodes[:5]:  # 显示前5个错误类型
            count = retcode_stats[retcode]
            percentage = (count / total_requests) * 100
            description = retcode_descriptions.get(retcode, "未知错误")
            html_content += f"• Retcode {retcode}: {description} ({count} 次, {percentage:.2f}%)<br>"
    
    html_content += """
        </div>
        
        <div class="info">
            <strong>📝 Report Notes</strong><br>
            • This report is generated based on Locust load test results<br>
            • Retcode 0 indicates successful requests, other values represent different types of errors<br>
            • Recommend focusing on retcode types with high error rates<br>
            • For detailed logs, please check the Locust runtime logs
        </div>
    </div>
</body>
</html>
"""
    
    # Write to file
    try:
        with open(output_file, 'w', encoding='utf-8') as f:
            f.write(html_content)
        print(f"HTML report generated: {output_file}")
        print(f"Please open in browser to view: file://{os.path.abspath(output_file)}")
    except Exception as e:
        print(f"Error generating HTML report: {e}")

def main():
    parser = argparse.ArgumentParser(description='Generate Retcode Analysis Report')
    parser.add_argument('json_file', help='Input JSON statistics file')
    parser.add_argument('-o', '--output', help='Output HTML filename')
    
    args = parser.parse_args()
    
    generate_html_report(args.json_file, args.output)

if __name__ == "__main__":
    # If no command line arguments, find the latest JSON file
    import sys
    import glob
    
    if len(sys.argv) == 1:
        # Find the latest retcode statistics JSON file
        json_files = glob.glob("retcode_stats_*.json")
        if json_files:
            latest_file = max(json_files, key=os.path.getctime)
            print(f"Found latest statistics file: {latest_file}")
            generate_html_report(latest_file)
        else:
            print("No retcode statistics JSON file found")
            print("Usage: python generate_report.py <json_file>")
    else:
        main()